<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入商品编号" v-model="listQuery.productCode">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-download" @click="handleDownload" :loading="downloadLoading">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
       <el-table-column type="expand">
         <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">

             <el-form-item label="商品编号：">
              <span>{{ props.row.productCode }}</span>
             </el-form-item>

            <el-form-item label="商品名称：">
              <span>{{ props.row.productName }}</span>
            </el-form-item>

            <el-form-item label="推荐标题:">
              <span>{{ props.row.recommendContent }}</span>
            </el-form-item>

             <el-form-item label="推荐位置:">
              <span>{{ props.row.recommendCode | formatRecommendCode }}</span>
             </el-form-item>
       
            <el-form-item label="排序:">
              <span>{{ props.row.sortOrder }}</span>
            </el-form-item>

            <el-form-item label="状态:">
              <span>{{ props.row.recommendStatus === 1 ? '可用' : '停用' }}</span>
            </el-form-item>

            <el-form-item label="创建时间:">
              <span>{{ props.row.createTime }}</span>
            </el-form-item>
            <el-form-item label="修改时间:">
              <span>{{ props.row.updateTime }}</span>
            </el-form-item>
           
            <el-form-item label="备注:">
              <span>{{ props.row.comment }}</span>
            </el-form-item>
          </el-form>          
        </template>
      </el-table-column>

      <el-table-column align="center" type="selection" width="55" prop="remmendId"/>

      <el-table-column align="center" min-width="100px" label="商品编号" prop="productCode"/>


      <el-table-column align="center" min-width="200px" label="推荐位置" prop="recommendCode"
        :filters="[{ text: '首页轮播图', value: '0' }, { text: '首页一行', value: '1' }, { text: '首页半行', value: '2' }, { text: '分类推荐', value: '3' }]" :filter-method="filterRecommendCode">
         <template slot-scope="scope">
         <el-tag >{{scope.row.recommendCode| formatRecommendCode}}</el-tag>
      </template>
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="推荐标题" prop="recommendTitle" sortable/>
      
      <el-table-column align="center" min-width="100px" label="排序" prop="sortOrder" sortable/>

      <el-table-column align="center" min-width="200px" label="状态" prop="recommendStatus"
       :filters="[{ text: '停用', value: 0 }, { text: '可用', value: 1 }]" :filter-method="filterStatus">
       <template slot-scope="scope">
         <el-tag :type="scope.row.recommendStatus === 1 ?  'success' : 'error' ">{{scope.row.recommendStatus === 1 ? '可用' : '停用'}}</el-tag>
       </template> 
      </el-table-column>

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="cancel">
       <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="商品编号" prop="productCode">
          <el-input v-model="dataForm.productCode"></el-input>
        </el-form-item>

        <el-form-item label="推荐标题" prop="recommendTitle">
          <el-input v-model="dataForm.recommendTitle"></el-input>
        </el-form-item>

        <el-form-item label="推荐图片" prop="recommendImage">
          <el-upload  :file-list="listRecommendImage" action="#" name="file" list-type="picture" :show-file-list="true" :limit="1" :http-request="uploadUrl" :on-remove="removeImage">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="推荐位置" prop="recommendCode">
          <el-select v-model="dataForm.recommendCode" placeholder="请选择">
             <el-option v-for="(value,key,index) in listRecommends" :key="index" :label="value" :value="key"/> 
          </el-select>
        </el-form-item>        

        <el-form-item label="排序" prop="sortOrder">
          <el-input type="number" v-model="dataForm.sortOrder" placeholder="数字越小越靠前"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="recommendStatus">
          <el-select v-model="dataForm.recommendStatus" placeholder="请选择">
            <el-option label="启用" :value="1">
            </el-option>
            <el-option label="禁用" :value="0">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
 .demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>

<script>
import { listAd, createAd, updateAd, deleteAd ,listRecommendType } from '@/api/ad'
import client from '../../utils/alioss'
import { createStorage } from '@/api/storage'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'Ad',
  directives: {
    waves
  },
  data() {
    return {
      list: undefined,
      total: undefined,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        productCode: '',
        sort: 'recommend_id'
      },

      //推荐位集合
      listRecommends: [],
      //推荐图片
      listRecommendImage:[],

      dataForm: {
       recommendId:'',
       productCode:'',
       recommendCode:'',
       recommendImage:'',
       recommendTitle:'',
       recommendStatus:1,
       sortOrder:undefined,
       comment:''
      },
     
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        productCode: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
        recommendTitle: [{ required: true, message: '推荐标题不能为空', trigger: 'blur' }],
        recommendCode: [{ required: true, message: '推荐位置不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
    filters: {
    // 推荐位显示转换
    formatRecommendCode(code) {
      const formatRecommendCodeMap = {
        "0": "首页轮播图",
        "1": "首页一行",
        "2": "首页半行",
        "3": "分类推荐位"
      };
      return formatRecommendCodeMap[code];
    }
  },
  methods: {

    //状态筛选
    filterStatus(value, row) {
      return row.recommendStatus === value;
    },
    //筛选推荐位置
    filterRecommendCode(value, row) {
      return row.recommendCode === value;
    },

    getList() {
      this.listLoading = true
      listAd(this.listQuery).then(response => {
        this.list = response.data.data.recommends
        this.total = response.data.data.page.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
       recommendId:'',
       productCode:'',
       recommendCode:'',
       recommendTitle:'',
       recommendImage:'',
       sortOrder:undefined,
       recommendStatus:1,
       comment:''
      }
    },

    //获取推荐位集合
    getRecommendTypes(){
      if(this.listRecommends.length === 0 ){
        listRecommendType().then(res =>{
          this.listRecommends = res.data.data
        
        })
      }
    },
  //dialog关闭取消
    cancel(){
      //dialog消失
     this.dialogFormVisible = false
     this.listRecommendImage = []
     
    },
    //上传图片
    uploadUrl(file) {
      var fileName = 'banner' + file.file.uid + '.png'
      client.put('aimi_store/' + fileName, file.file).then(result => {
        
        this.dataForm.recommendImage=result.url
      })
    },
    //删除图片
    removeImage(file,fileList){
      this.dataForm.recommendImage = ''
  
    },
    //添加商品界面
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getRecommendTypes();
    },

    //添加推荐商品
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAd(this.dataForm).then(response => {
            console.info(response.data.data)
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    //编辑界面
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      //显示图片
      let recommendImages = []
      if(this.dataForm.recommendImage !== '' &&this.dataForm.recommendImage !==null){
        recommendImages.push({name:'',url:this.dataForm.recommendImage})
        this.listRecommendImage=recommendImages
      }
      this.getRecommendTypes();
    },

    //修改
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateAd(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    //删除商品推荐位
    handleDelete(row) {
      deleteAd(row.recommendId).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['广告ID', '广告标题', '广告内容', '广告图片', '广告位置', '活动链接', '是否启用']
        const filterVal = ['id', 'name', 'content', 'url', 'postion', 'link', 'enabled']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '广告信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>